# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/1/22
# @File   : IC18_PastLoanCardQuasiMaxConOvduMons.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:过去五年贷款和（准）贷记卡最长连续逾期或透支月数
code:IC18_PastLoanCardQuasiMaxConOvduMons
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(table_Name):
    try:
        data = IC_DSJ['data'].get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}]
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def isReportNo(x):
    try:
        if len(x) == 1:
            is_reportno = x[0].get('reportNo')
            if is_reportno in null_type_list:
                return False
            else:
                return True
        else:
            return True
    except:
        return False

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False



def PastLoanCardQuasiMaxConOvduMonsPre(*args):
    try:
        # 贷款明细表
        icrLoanInfo002LoanList = getTable(args[0])
        # 贷款5年逾期记录表
        icrLatest5YearOverdueDetailList = getTable(args[1])

        if icrLoanInfo002LoanList is None:
            result1 = None
        elif icrLoanInfo002LoanList == [{}]:
            result1 = []
        else:
            flag = []
            result1 = []

            for row1 in icrLoanInfo002LoanList:
                if row1.get('latest24State') in null_type_list:
                    if row1.get('account') not in null_type_list:
                        result1.append(0)
                    else:
                        flag.append(None)
                else:
                    if args[0] == 'ICRStdLoancardInfo002*Std':
                        latest24State = row1.get('latest24State')
                        pattern = re.compile('[3-7]')
                        r = pattern.findall(latest24State)
                        #准贷记卡逾期超过2次才开始计算
                        count1 = float(max(r))-2 if len(r) != 0 else 0
                    else:
                        latest24State = row1.get('latest24State')
                        pattern = re.compile('[1-7]')
                        r = pattern.findall(latest24State)
                        count1 = float(max(r)) if len(r) != 0 else 0

                    if row1.get('account') not in null_type_list:
                        result1.append(count1)
                    else:
                        flag.append(None)
                        continue
            if len(flag) == len(icrLoanInfo002LoanList):
                result1 = None

        #5年逾期记录
        if icrLatest5YearOverdueDetailList is None:
            result2 = None
        elif icrLatest5YearOverdueDetailList == [{}]:
            result2 = []
        else:
            flag = []
            result2 = []
            #
            if args[1] == 'ICRLatest5YearOverdueDetail*Std':
                for row2 in icrLatest5YearOverdueDetailList:
                    if row2.get('account') not in null_type_list \
                            and row2.get('lastMonths') not in null_type_list \
                            and isfloat(row2.get('lastMonths')):
                        if 1<= float(row2.get('lastMonths')) <= 7:
                            if float(row2.get('lastMonths')) >= 2:
                                result2.append(float(row2.get('lastMonths'))-2)
                            else:
                                pass
                        else:
                            flag.append(None)
                            continue
                    else:
                        flag.append(None)
                        continue
            else:
                for row2 in icrLatest5YearOverdueDetailList:
                    if row2.get('account') not in null_type_list \
                            and row2.get('lastMonths') not in null_type_list and isfloat(row2.get('lastMonths')):
                        if 1 <= float(row2.get('lastMonths')) <= 7:
                            result2.append(float(row2.get('lastMonths')))
                        else:
                            flag.append(None)
                            continue
                    else:
                        flag.append(None)
                        continue

            if len(flag) == len(icrLatest5YearOverdueDetailList):
                result2 = None
        #若全为None 返回None，否则置为0
        if result1 is None and result2 is None:
            return None
        else:
            result1 = max(result1) if result1!=[] and result1 != None else 0
            result2 = max(result2) if result2!=[] and result2 != None else 0
            return max(result1, result2)
    except:
        return None

def IC18_PastLoanCardQuasiMaxConOvduMons():
    try:
        # 贷款信息
        dk = PastLoanCardQuasiMaxConOvduMonsPre(*('ICRLoanInfo002*Loan', 'ICRLatest5YearOverdueDetail*Loan'))
        # 贷记卡信息
        djk = PastLoanCardQuasiMaxConOvduMonsPre(*('ICRLoancardInfo002*Card', 'ICRLatest5YearOverdueDetail*Card'))
        # 准贷记卡信息
        zdjk = PastLoanCardQuasiMaxConOvduMonsPre(*('ICRStdLoancardInfo002*Std', 'ICRLatest5YearOverdueDetail*Std'))
        if dk is None and djk is None and zdjk is None:
            return u'缺失值'
        else:
            dk = dk if dk != None else 0
            djk = djk if djk != None else 0
            zdjk = zdjk if zdjk != None else 0
            return max(dk, djk, zdjk)
    except:
        return u'缺失值'

result = IC18_PastLoanCardQuasiMaxConOvduMons()